import { login, logout, sendVerifyCode } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    phone: '',
    street: '',
    roleFlag: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_STREET: (state, street) => {
    state.street = street
  },
  SET_ROLEFLAG: (state, roleFlag) => {
    state.roleFlag = roleFlag
  }
}

const actions = {
  // 发送验证码
  SendVerifyCode({ commit }, data) {
    return new Promise((resolve, reject) => {
      sendVerifyCode(data)
        .then(response => {
          Message({
            message: '发送成功',
            type: 'success',
            duration: 3 * 1000
          })
          resolve()
        })
        .catch(() => {
          reject()
        })
    })
  },
  // 登录
  login({ commit }, userInfo) {
    const { phone, vcode } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone: phone.trim(), vcode: vcode }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_NAME', data.realName)
        commit('SET_PHONE', data.phone)
        commit('SET_STREET', data.street)
        commit('SET_ROLEFLAG', data.roleFlag)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

